package com.matt.sooncleaner.notification

import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.content.pm.ResolveInfo
import android.provider.Settings
import androidx.collection.ArraySet
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.Utils
import com.matt.sooncleaner.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.CopyOnWriteArraySet


object NotificationHelper {
    private const val KEY_ENABLE_NOTIFICATION_BLOCK = "enableNotificationBlock"
    private val mEnablePackageList = CopyOnWriteArraySet<String>()

    private val mLauncherIntent by lazy {
        val resolveIntent = Intent(Intent.ACTION_MAIN, null)
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER)
        resolveIntent
    }

    init {
        val enablePackage = SPUtils.getInstance().getString(KEY_ENABLE_NOTIFICATION_BLOCK, "")
        if (enablePackage.isNotEmpty()) {
            mEnablePackageList.addAll(enablePackage.split("|"))
        }
    }

    fun isEnableBlock(packageName: String) = packageName in mEnablePackageList

    fun setEnableBlock(packageName: String, isEnable: Boolean) {
        if (isEnable) {
            mEnablePackageList.add(packageName)
        } else {
            mEnablePackageList.remove(packageName)
        }
        SPUtils.getInstance().put(
            KEY_ENABLE_NOTIFICATION_BLOCK,
            mEnablePackageList.joinToString("|")
        )
    }

    @SuppressLint("QueryPermissionsNeeded")
    suspend fun getInstallAppList(): List<AppInfo> {
        return withContext(Dispatchers.IO) {
            val pm = Utils.getApp().packageManager
            val packageList = pm.getInstalledPackages(PackageManager.GET_ACTIVITIES)
//            val resolveinfoList: List<ResolveInfo> = pm
//                .queryIntentActivities(mLauncherIntent, 0)
            val appInfoList = mutableListOf<AppInfo>()
            packageList.forEach {
                if (it.applicationInfo.isTripartiteApp() && Utils.getApp().packageName != it.packageName) {
                    appInfoList.add(it.toAppInfo(pm))
                }
            }
            return@withContext appInfoList
        }
    }

    private fun ApplicationInfo.isTripartiteApp(): Boolean {
        return flags and ApplicationInfo.FLAG_SYSTEM == 0
    }

    fun isNotificationListenerEnable(): Boolean {
        var enable = false;
        val packageName = Utils.getApp().packageName
        val flat = Settings.Secure.getString(
            Utils.getApp().contentResolver,
            "enabled_notification_listeners"
        );
        if (flat != null) {
            enable = flat.contains(packageName);
        }
        return enable;
    }

    fun gotoNotificationAccessSetting(context: Context): Boolean {
        try {
            val intent = Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            return true
        } catch (e: ActivityNotFoundException) {
            try {
                val intent = Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                val cn = ComponentName(
                    "com.android.settings",
                    context.getString(R.string.settings_notification)
                );
                intent.component = cn
                intent.putExtra(":settings:show_fragment", "NotificationAccessSettings");
                context.startActivity(intent);
                return true;
            } catch (ex: Exception) {
                ex.printStackTrace();
            }
            return false;
        }
    }
}